<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form
        ref="queryRef"
        :model="state.queryParams"
        :inline="true"
        v-show="state.showSearch"
        label-width="90px"
    >
      <el-form-item label="用户ID" prop="membersId">
        <el-input
            v-model="state.queryParams.membersId"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券ID" prop="couponId">
        <el-input
            v-model="state.queryParams.couponId"
            placeholder="请输入优惠券ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="state.queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
        >
          <el-option
              v-for="dict in use_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优惠券来源" prop="sourceType">
        <el-select
            v-model="state.queryParams.sourceType"
            placeholder="请选择优惠券来源"
            clearable
            style="width: 150px"
        >
          <el-option
              v-for="dict in source_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button
            type="primary"
            plain
            :icon="Plus"
            @click="handleAdd"
            v-hasPermi="['transaction:UserCoupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="success"
            plain
            :icon="Edit"
            :disabled="state.single"
            @click="handleUpdate"
            v-hasPermi="['transaction:UserCoupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="danger"
            plain
            :icon="Delete"
            :disabled="state.multiple"
            @click="handleDelete"
            v-hasPermi="['transaction:UserCoupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="warning"
            plain
            :icon="Download"
            @click="handleExport"
            v-hasPermi="['transaction:UserCoupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table
        :data="state.tableData"
        border
        v-loading="state.loading"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template #default="{ row }">
          <dict-tag :options="coupon_type" :value="row.couponType" />
        </template>
      </el-table-column>
      <el-table-column label="优惠券来源" align="center" prop="sourceType">
        <template #default="{ row }">
          <dict-tag :options="source_type" :value="row.sourceType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <dict-tag :options="use_status" :value="row.status" />
          <el-tooltip content="查看订单详情" placement="top">
            <el-button
                :icon="More"
                type="primary"
                link
                circle
                size="small"
                @click.stop="showOrderDetail(row)"
                style="margin-left: 8px"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button
              link
              type="primary"
              :icon="Edit"
              @click="handleUpdate(row)"
              v-hasPermi="['transaction:UserCoupon:edit']"
          >修改</el-button>
          <el-button
              link
              type="primary"
              :icon="Delete"
              @click="handleDelete(row)"
              v-hasPermi="['transaction:UserCoupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="state.orderDialogVisible" title="优惠券使用记录" width="700px" append-to-body>
      <div v-if="state.noRecord">
        <p>没有使用记录</p>
      </div>
      <div v-else>
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ state.orderDetail.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ state.orderDetail.address }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ state.orderDetail.paymentTime }}</el-descriptions-item>
          <el-descriptions-item label="商品总额">{{ state.orderDetail.itemsAmount }}</el-descriptions-item>
          <el-descriptions-item label="运费">{{ state.orderDetail.shippingFee }}</el-descriptions-item>
          <el-descriptions-item label="优惠券金额">{{ state.orderDetail.couponAmount }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">{{ state.orderDetail.totalAmount }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin: 20px 0 10px">商品列表</h3>
        <el-table :data="state.orderItems" border>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="specInfo" label="规格" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="price" label="单价" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 新增/修改表单弹窗 -->
    <el-dialog v-model="state.open" :title="state.title" width="500px" append-to-body>
      <el-form ref="UserCouponRef" :model="state.form" :rules="rules" label-width="100px">
        <el-form-item label="用户ID" prop="membersId">
          <el-input v-model="state.form.membersId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="优惠券ID" prop="couponId">
          <el-input v-model="state.form.couponId" placeholder="请输入优惠券ID" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="state.form.status" placeholder="请选择状态">
            <el-option
                v-for="dict in use_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="来源" prop="sourceType">
          <el-select v-model="state.form.sourceType" placeholder="请选择来源">
            <el-option
                v-for="dict in source_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="state.queryParams.pageNum"
        v-model:limit="state.queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, toRefs, defineOptions } from 'vue'
import { listUserCoupon, getUserCoupon, delUserCoupon, addUserCoupon, updateUserCoupon } from '@/api/transaction/UserCoupon'
import { getShoporder } from '@/api/transaction/shoporder'
import { getShoporderitem } from '@/api/transaction/shoporderitem'
import { Search, Edit, Delete, Plus, Refresh, Download, More } from '@element-plus/icons-vue'

defineOptions({ name: 'UserCoupon' })

const { proxy } = getCurrentInstance()
const { source_type, use_status, coupon_type } = proxy.useDict('source_type', 'use_status', 'coupon_type')

const state = reactive({
  tableData: [],
  open: false,
  loading: false,
  showSearch: true,
  ids: [],
  single: true,
  multiple: true,
  total: 0,
  title: '',
  orderDialogVisible: false,
  noRecord: false,
  orderDetail: {},
  orderItems: [],
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    membersId: null,
    couponId: null,
    status: null,
    receivedTime: null,
    usedTime: null,
    orderId: null,
    sourceType: null
  }
})

const rules = {
  membersId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  couponId: [{ required: true, message: '优惠券ID不能为空', trigger: 'blur' }]
}

const normalizeToArray = (x) => Array.isArray(x) ? x : Array.isArray(x?.data) ? x.data : Array.isArray(x?.rows) ? x.rows : []

const getList = () => {
  state.loading = true
  listUserCoupon(state.queryParams)
      .then(res => {
        state.tableData = normalizeToArray(res?.rows ?? res?.data ?? res)
        state.total = res?.total ?? 0
      })
      .catch(() => {
        state.tableData = []
        state.total = 0
      })
      .finally(() => {
        state.loading = false
      })
}

const showOrderDetail = async (row) => {
  try {
    // 如果订单详情为 null，直接显示无记录
    if (!row.orderId) {
      state.orderDetail = {}
      state.orderItems = []
      state.noRecord = true
      state.orderDialogVisible = true
      return
    }

    const detailRes = await getShoporder(row.orderId)
    // 订单详情
    state.orderDetail = detailRes?.data ?? detailRes ?? {}

    const itemsRes = await getShoporderitem(row.orderId)
    // 商品列表：无论返回数组还是单对象，都包成数组
    const rawItems = itemsRes?.data ?? itemsRes ?? []
    state.orderItems = Array.isArray(rawItems) ? rawItems : [rawItems]

    // 没记录的判断
    state.noRecord = state.orderItems.length === 0

    // 数据赋值完后再打开弹窗
    state.orderDialogVisible = true
  } catch (e) {
    console.error('获取订单信息失败', e)
    state.orderItems = []
    state.orderDetail = {}
    state.noRecord = true
  }
}



const cancel = () => {
  state.open = false
  state.form = {}
}

const handleQuery = () => {
  state.queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  proxy.resetForm('queryRef')
  handleQuery()
}

const handleSelectionChange = (selection) => {
  state.ids = selection.map(item => item.id)
  state.single = selection.length !== 1
  state.multiple = !selection.length
}

const handleAdd = () => {
  cancel()
  state.open = true
  state.title = '添加用户优惠券记录'
}

const handleUpdate = (row) => {
  cancel()
  const id = row?.id || state.ids
  getUserCoupon(id).then(res => {
    state.form = res?.data ?? res
    state.open = true
    state.title = '修改用户优惠券记录'
  })
}

const submitForm = () => {
  proxy.$refs.UserCouponRef.validate(valid => {
    if (!valid) return
    const api = state.form.id != null ? updateUserCoupon : addUserCoupon
    api(state.form).then(() => {
      proxy.$modal.msgSuccess(state.form.id ? '修改成功' : '新增成功')
      state.open = false
      getList()
    })
  })
}

const handleDelete = (row) => {
  const ids = row?.id || state.ids
  proxy.$modal.confirm(`是否确认删除用户优惠券记录编号为 "${ids}" 的数据项？`)
      .then(() => delUserCoupon(ids))
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
}

const handleExport = () => {
  proxy.download('transaction/UserCoupon/export', { ...state.queryParams }, `UserCoupon_${Date.now()}.xlsx`)
}

getList()
</script>
